// import _local from "../../cache/_local";
import _regular from "../../../utils/_regular";
import _object from "../../../utils/_object";
import lib_activity from "../../../api/lib_activity";
import _layer from "../../../common/_layer";
import _time from "../../../utils/_time"
import swiperData from "../../../common/_swiperdata";
import lib_clue from "../../../api/lib_clue";
import _report from "../../../common/_report"
import lib_tiktok from "../../../api/lib_tiktok";
import _city from "../../../cache/_city";
import _series from "../../../cache/_series";
import _activity from "../../../cache/_activity";
import lib_city from "../../../api/lib_city";
import lib_car from "../../../api/lib_car";
import _location from "../../../cache/_location";
import _multiple_ui from "../../../cache/_multiple_ui";


Page({
  data: {
    /**页面参数 */
    activity_id: '', //活动ID
    channel: 3, //渠道
    tids: 0, // 模板ID
    clickid: '', //点击上报id


    /**项目信息 */

    custom_car: 0, // 是否自定义车型库
    tid: 0, // 有无车型库
    share_theme: '', //分享描述
    stime: 0, // 项目开始时间
    etime: 0, // 项目结束时间
    ui: {
      head: '', //头图
      tail: '', //详情图
      share: '', //分享图
      bg_color: '', //表单背景色
      font_color: '', //文本颜色
      btn_bg_color: '', //按钮背景色
      btn_font_color: '', //按钮文本颜色
      btn_text: '', //按钮文本值
      btm_btn_text: '', //底部按钮文本
      is_banner: 0, //是否有轮播图
      is_counter: 0, //是否有倒计时
      is_copyright: 1, //协议
      jmp_url: 0, //0-报名成功;1-帮朋友报名;2-置换二手车;3-邮寄门票
    },

    /**form表单 */
    city: '', //城市
    brand: '', //品牌
    series: '', //车型
    name: '', // 姓名
    phone: '', //电话


    //城市联级选择
    is_city: false, //表单城市项，默认无城市
    is_stop: false, //活动是否已结束


    /**城市相关 */

    swiper_list: [], //轮播

    guiding_price: '???',
    min_price: '???',
    final_price: '???',
    total_queries: '35,122', //累计查询人数
    innerHeight: 827,


    // 弹框部分
    is_policy: false, //隐私协议
    is_dialog_car: false,
    brand_show: false,
    series_show: false,


    citys: [],
    hot: [], //热门品牌
    brand_list: [], //品牌
    series_list: [], //车型
    letter: [], //字母
    current_letter: '', //高亮字母
    toView: '',

    brand_id: 0,
    brand_name: '',
    series_id: 0,
    series_name: '',

    province: '',
    location: '',
    city: '',

  },

  onLoad: function (options) {
    // 参数
    if (_object._length(options) > 0 && options.hasOwnProperty('activity_id') && options.activity_id > 0) {
      this.setData({
        activity_id: options.activity_id
      })
    }

    if (_object._length(options) > 0 && options.hasOwnProperty('tids') && options.tids > 0) {
      this.setData({
        tids: options.tids
      })
    }

    if (_object._length(options) > 0 && options.hasOwnProperty('clickid')) {
      this.setData({
        clickid: options.clickid
      })
    }

  },
  onShow() {
    /**
     * README: 参数activity_id必填，tids选填，clickid为监测上报id
     */

    //存参数
    _activity.set({
      'activity_id': this.data.activity_id,
      'tids': this.data.tids,
      'clickid': this.data.clickid
    })
    // console.log(this.data.clickid, '监测id');

    _multiple_ui.set({
      'is_multiple': 1
    })

    this.setData({
      swiper_list: swiperData.time_swiper_1,
    });

    this.init_info()

  },

  onReady() {
    //进入页面直接获取定位城市
    if (!_city.get()) {
      this.init_local_city()
    }
  },

  init_info() {
    const { activity_id, tids } = this.data

    lib_activity.info(activity_id, tids).then((res) => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }

      let data = res.data
      this.setData({
        tid: data.activity.tid, // 类型
        custom_car: data.activity.custom_car
      })


      if (data.ui == null) {
        this.setData({ ui: {} })
        return;
      }
      this.setData({ ui: data.ui })

      // console.log(this.data.ui, 'UI模板');

      // 项目结束
      if (!data.activity.state || (_time._current() > data.activity.etime)) {
        this.setData({
          is_stop: true
        })
        return;
      }

      // 判断是否有城市
      let city = []
      if (data.activity.city) {
        city = data.activity.city.split(',');
      }
      if (city.length == 1 && city[0] > 0) {
        //单城市项目
        this.setData({
          is_city: false
        })
      } else {
        //多城市项目
        this.setData({
          is_city: true
        })
        this.getCity(data.activity.city)
      }

      this.init_brand(activity_id, this.data.custom_car);

    })
  },

  //获取城市
  getCity(city) {
    lib_city.list(city).then(res => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }
      this.setData({
        citys: res.data
      })
    })
  },

  //获取品牌
  init_brand(activity_id, custom_car) {
    console.log(1111);
    lib_car.brand(activity_id, custom_car).then(res => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }
      this.setData({
        hot: res.data.hot,
        brand_list: res.data.brand,
        letter: res.data.letter,
      })
    })
  },

  //获取车型
  init_series(activity_id, custom_car, brand_id) {
    lib_car.series(activity_id, custom_car, brand_id).then(res => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }
      this.setData({
        brand_show: false,
        series_show: true,
        series_list: res.data
      })
    })
  },

  //字母
  clk_letter(e) {
    this.setData({
      current_letter: e.currentTarget.dataset.item,
      toView: e.currentTarget.dataset.item,
    })
  },

  clk_brand(e) {
    const { brand_id, brand_name } = e.currentTarget.dataset.item
    this.setData({
      brand_id: brand_id,
      brand_name: brand_name,
      brand_show: false,
      series_show: true,
    })
    // 请求车型
    const { activity_id, custom_car } = this.data
    // this.init_series(activity_id, custom_car, brand_id)
    lib_car.series(activity_id, custom_car, brand_id).then(res => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }
      this.setData({
        series_list: res.data
      })
    })
  },
  //车型
  clk_series(e) {
    const { series_name, series_id } = e.currentTarget.dataset.item

    this.setData({
      series: this.data.brand_name + '/' + series_name,
      series_name: series_name,
      series_id: series_id,
    })


    let hide_guiding_price;
    let hide_final_price;
    let hide_msrp_min;
    // console.log(typeof this.data.brand_id, 'series_id');
    // 计算三类价格
    hide_guiding_price = (Number(series_id + this.data.brand_id) / 1.5).toFixed(2).toString().split('.')
    hide_guiding_price[0] = '?'

    hide_final_price = (Number(series_id + this.data.brand_id) / 1.3).toFixed(2).toString().split('.'); //成交底价 = 最低价*1.1
    hide_final_price[0] = '?'

    hide_msrp_min = (Number(series_id + this.data.brand_id) /  0.9).toFixed(2).toString().split('.'); //最低报价 = 最低价*0.9
    hide_msrp_min[0] = '?'

    this.setData({
      guiding_price: hide_guiding_price[0] + '.' + hide_guiding_price[1],
      min_price: hide_msrp_min[0] + '.' + hide_msrp_min[1],
      final_price: hide_final_price[0] + '.' + hide_final_price[1],
    })

    setTimeout(() => {
      this.setData({
        is_dialog_car: false
      })
    }, 4)

    //存对应的车型
    _series.set({ 'series_name': series_name, 'series_id': series_id })

  },

  //获取本机手机号
  getPhoneNumber(e) {
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      const iv = e.detail.iv;
      const encryptedData = e.detail.encryptedData;
      lib_tiktok.phone(encryptedData, iv).then((res) => {
        if (res.code == 0) {
          this.setData({ phone: res.data.phone })

        } else {
          _layer.message(res.msg)
        }
      })
    }
  },

  //进入页面定位城市
  init_local_city() {
    tt.getLocation({
      type: 'gcj02',
      success: (res) => {
        if (res.errMsg == 'getLocation:ok') {
          // 定位到的城市信息（iOS 仅在抖音 / 抖音 Lite 20.5.0 及以上版本返回此字段）
          if (res.city) {

            //可以直接获取城市回传表单，不做城市列表限制
            this.setData({ city: res.city })
            _location.set(res.city)
            //存city
            _city.set(this.data.city)
          }
        } else {
          _layer.message('定位失败')
        }
      },
      fail: (errMsg) => {
        if (errMsg) {
          // _layer.message('已拒绝开启定位')
        }
      },
      complete: () => {
      }
    });

  },
  //定位城市
  get_localCity(e) {
    this.getLocation(e)
  },
  getLocation(e) {
    tt.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log(res, '===');
        if (res.errMsg == 'getLocation:ok') {
          // 定位到的城市信息（iOS 仅在抖音 / 抖音 Lite 20.5.0 及以上版本返回此字段）
          if (res.city) {
            // this.data.citys.forEach((item, index) => {
            //   item.children.forEach((it, id) => {
            //     if (it.name == res.city) {
            //       this.setData({
            //         city: it.name,
            //         province: item.name,
            //         location: res.city
            //       })
            //     }
            //     if (res.city == '北京市') {
            //       this.setData({
            //         city: '北京',
            //         province: item.name,
            //         location: res.city
            //       })
            //     }
            //   })
            // })

            //可以直接获取城市回传表单，不做城市列表限制
            this.setData({ city: res.city })
            _location.set(res.city)
            //存city
            _city.set(this.data.city)
          }
        }
      },
      fail: (errMsg) => {
        if (errMsg) {
          // _layer.message('已拒绝开启定位')
        }
      },
      complete: () => {
      }
    });
  },

  //跳转
  toCity() {
    tt.navigateTo({
      url: `/packageMy/pages/multiplecity/multiplecity?city=${this.data.city}`,
    });
  },
  //绑定
  ChangePhone(e) {
    this.setData({ phone: e.detail });
  },
  ChangeName(e) {
    this.setData({ name: e.detail });
  },

  // 弹框
  ChangeBrandFlag() {
    this.setData({
      is_dialog_car: !this.data.is_dialog_car,
      brand_show: true,
      series_show: false
    })
  },

  close_dialog_car() {
    this.setData({
      is_dialog_car: false
    })
  },
  //阻止默认行为
  ChangeBrandStop() {
    this.setData({ is_dialog_car: true });
  },
  //返回
  goback() {
    this.setData({
      series_show: false,
      brand_show: true
    })
  },

  // 表单提交
  submit() {

    if (!this.data.series) {
      _layer.message('请选择车型')
      return;
    }
    if (!this.data.city) {
      _layer.message('请选择城市')
      return;
    }
    if (!this.data.name) {
      _layer.message('请输入姓名')
      return;
    }
    if (this.data.name && this.data.name.length > 50) {
      _layer.message('请输入正确的姓名')
      return;
    }
    if (!this.data.phone) {
      _layer.message('请输入手机号')
      return;
    }
    if (!_regular.is_mobile(this.data.phone)) {
      _layer.message('请输入正确的手机号')
      return;
    }
    // 报名
    let location = this.data.is_city ? this.data.city : '';
    let form_ui_id = this.data.ui.hasOwnProperty("id") ? this.data.ui.id : 0;

    let pages = getCurrentPages(); // 获取页面指针数组
    let currentPage = pages[pages.length - 1]; // 获取当前页
    let route = currentPage.route;
    // let { activity_id, tids } = currentPage.options;
    const { activity_id, tids } = this.data;
    let url = `${route}?activity_id=${activity_id}&tids=${tids}`

    let params = {
      activity_id: this.data.activity_id,
      channel_code: this.data.channel,
      location, // 省 + 市
      url,
      form_name: this.data.name,
      form_phone: this.data.phone,
      form_brand: this.data.brand_name,
      form_series: this.data.series_name,
      form_ui_id,
    }
    // console.log(params, '入参');
    // return;

    lib_clue.receive(params).then(res => {
      //监测
      if (res.code == 0) {
        _report._post(this.data.clickid)

      }
      //跳转地址
      tt.navigateTo({
        url: `/packageMy/pages/pricelist/pricelist`,
      });
    })
  },

  //分享
  async onShareAppMessage(option) {

    const { activity_id, tids, clickid } = this.data

    return {
      title: '查询底价',
      path: `/pages/multiple/common/common?activity_id=${activity_id}&tids=${tids}&clickid=${clickid}`, // ?后面的参数会在转发页面打开时传入onLoad方法
      imageUrl: '/assets/image/multiple_banner.jpg', // 支持本地或远程图片，默认是小程序 icon
      success(res) {
        console.log('分享成功', res);
      },
      fail() {
        console.log("转发发布器调起失败");
      },
    };
  },

  // 协议
  policy() {
    this.setData({
      is_policy: true
    })
  },
  close_policy() {
    this.setData({
      is_policy: false
    })
  },

});